package com.kaifamiao.wendao.servlet;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.service.TopicService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet( "/topic/publish/*" )
public class TopicPublishServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 应该对表单数据予以检查 (即数据校验)

        // 从表单中获取数据
        String title = request.getParameter( "title" );
        String content = request.getParameter( "content" );
        // 获取提交者的IP地址
        String ip = request.getRemoteAddr();

        HttpSession session = request.getSession();
        Customer c = (Customer)session.getAttribute( "customer" );

        // 创建 Topic 对象
        Topic t = new Topic();
        t.setTitle( title );
        t.setContent( content );
        t.setPublishIp( ip );
        // 当前已登录用户就是发布者
        t.setPublisher( c );

        TopicService ts = new TopicService();

        ts.save( t );

        // 发布成功后去往话题列表页面
        response.sendRedirect( request.getContextPath() + "/topic/list" );
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        // 从会话对象中获取名称是 customer 的属性值
        Customer c = (Customer)session.getAttribute( "customer" );
        // 检查用户是否已经登录
        if( c == null ){
            session.setAttribute( "message" , "请先登录" );
            response.sendRedirect( request.getContextPath() + "/customer/sign/in");
            return ;
        }

        String path = "/WEB-INF/pages/topic/publish.jsp" ;
        RequestDispatcher dispatcher = request.getRequestDispatcher( path );
        // 如果已经登录则去往发布页面
        dispatcher.forward( request , response );
    }
}
